"""
WebSocket连接管理器和消息队列系统
"""
import asyncio
from typing import List
from fastapi import WebSocket


class ConnectionManager:
    """WebSocket连接管理器"""
    
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        """接受新的WebSocket连接"""
        await websocket.accept()
        self.active_connections.append(websocket)
        print(f"[WebSocket] 新客户端连接，当前连接数: {len(self.active_connections)}")

    def disconnect(self, websocket: WebSocket):
        """断开WebSocket连接"""
        if websocket in self.active_connections:
            self.active_connections.remove(websocket)
            print(f"[WebSocket] 客户端断开连接，当前连接数: {len(self.active_connections)}")

    async def broadcast(self, message: str):
        """向所有连接的客户端广播消息"""
        print(f"[Broadcast] 发送消息到 {len(self.active_connections)} 个客户端: {message}")
        disconnected_connections = []
        for connection in self.active_connections:
            try:
                await connection.send_text(message)
            except Exception as e:
                print(f"[Broadcast] 发送消息失败: {str(e)}")
                disconnected_connections.append(connection)
        
        # 清理断开的连接
        for connection in disconnected_connections:
            self.disconnect(connection)


# 创建连接管理器实例
manager = ConnectionManager()

# 创建消息队列
message_queue = asyncio.Queue()

# 全局事件循环引用
main_event_loop = None


async def message_processor():
    """消息处理线程，从队列中读取消息并广播"""
    print("[消息处理器] 启动消息处理线程")
    while True:
        try:
            message = await message_queue.get()
            await manager.broadcast(message)
            message_queue.task_done()
        except Exception as e:
            print(f"[消息处理器] 处理消息时出错: {str(e)}")
            await asyncio.sleep(1)


def websocket_publish(message):
    """从其他线程向WebSocket客户端发送消息"""
    if main_event_loop:
        asyncio.run_coroutine_threadsafe(message_queue.put(message), main_event_loop)
    else:
        print("主事件循环未设置，无法发送消息。")


def set_main_event_loop(loop):
    """设置主事件循环"""
    global main_event_loop
    main_event_loop = loop


def start_message_processor():
    """启动消息处理器"""
    return asyncio.create_task(message_processor())